package com.zb.admin.service.Impl;

import com.zb.admin.mapper.AdUserMapper;
import com.zb.admin.service.AdUserService;
import com.zb.common.exception.CommonException;
import com.zb.model.dto.admin.AdLoginDto;
import com.zb.model.pojo.admin.AdUser;
import com.zb.model.vo.admin.AdLoginVo;
import com.zb.utils.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class AdUserServiceImpl implements AdUserService {

    @Autowired
    private AdUserMapper adUserMapper;
    @Override
    public Map login(AdLoginDto dto) {
        String name = dto.getName();
        String password = dto.getPassword();
        if(StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
            throw new CommonException(201, "缺少参数");
        }
        AdUser user = adUserMapper.findByName(name);
        if(user == null) {
            throw new CommonException(201, "用户不存在");
        }
        System.out.println(DigestUtils.md5DigestAsHex("123456".getBytes()));
        if(!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
            throw new CommonException(201, "密码错误");
        }
        System.out.println(DigestUtils.md5DigestAsHex("123456".getBytes()));
        String token = JwtUtil.createJWT(3600 * 24 * 1000, user.getId());
        AdLoginVo adLoginVo = new AdLoginVo();
        BeanUtils.copyProperties(user, adLoginVo);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("userInfo", adLoginVo);
        return map;
    }
}
